from flask import jsonify, request, Response
from supermarket.app import app, db, redis_store
from supermarket.app.models import Supplier
import csv
from io import StringIO

# 供应商管理的CRUD操作
@app.route('/suppliers', methods=['GET'])
def get_suppliers():
    try:
        suppliers = Supplier.query.all()
        serialized_suppliers = [supplier.to_dict() for supplier in suppliers]
        return jsonify(serialized_suppliers), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/suppliers/<int:id>', methods=['GET'])
def get_supplier(id):
    try:
        supplier = Supplier.query.get_or_404(id)
        serialized_supplier = supplier.to_dict()
        return jsonify(serialized_supplier), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/suppliers', methods=['POST'])
def create_supplier():
    try:
        data = request.get_json()
        new_supplier = Supplier(**data)
        db.session.add(new_supplier)
        db.session.commit()
        return jsonify(new_supplier.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/suppliers/<int:id>', methods=['PUT'])
def update_supplier(id):
    try:
        supplier = Supplier.query.get_or_404(id)
        data = request.get_json()
        for key, value in data.items():
            setattr(supplier, key, value)
        db.session.commit()
        return jsonify(supplier.to_dict()), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/suppliers/<int:id>', methods=['DELETE'])
def delete_supplier(id):
    try:
        supplier = Supplier.query.get_or_404(id)
        db.session.delete(supplier)
        db.session.commit()
        return jsonify({'message': 'Supplier deleted'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400

# 导出CSV
@app.route('/suppliers/export/csv', methods=['GET'])
def export_suppliers_csv():
    try:
        suppliers = Supplier.query.all()
        output = StringIO()
        writer = csv.writer(output)
        # 写入CSV头部
        writer.writerow(['id', 'name', 'short_name', 'address', 'phone', 'email', 'contact', 'contact_phone', 'remark'])
        # 写入CSV行
        for supplier in suppliers:
            writer.writerow([supplier.id, supplier.name, supplier.short_name, supplier.address, supplier.phone,
                             supplier.email, supplier.contact, supplier.contact_phone, supplier.remark])
        output.seek(0)
        return Response(output, mimetype='text/csv', headers={'Content-Disposition': 'attachment; filename=suppliers.csv'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400
